package com.shuhe.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Base64 {

    public static byte[] hexStringtoBytes(String hexString) {
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    //将BASE64存成照片
    public static void convertBase64ToFile(String fileBase64String, String fileName) {


        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);

            file = new File(fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);

            bos.close();
            fos.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    public static String fileConvertBase64(String fileName) throws Exception {
        FileInputStream in = new FileInputStream(new File(fileName));
        int len = -1;
        byte[] by = new byte[1024];
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        while ((len = in.read(by)) != -1) {
            data.write(by, 0, len);
        }
        return byteConvertBase64(data.toByteArray());
    }

    public static String byteConvertBase64(byte[] pictureData) {
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(pictureData);
        base64Str = base64Str.replaceAll("\n", "");
        base64Str = base64Str.replaceAll("\r", "");
        return base64Str;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(fileConvertBase64("D:\\java\\jetty-server\\src\\main\\resources\\template\\images\\4.jpg"));
    }
}
